<template>
  <div class="main">
    <div class="title">查询可做订单</div>
    <div class="btn-group">
      
      <el-button type="primary" :loading="refreshLoading" @click="getVender"
        >查询</el-button
      >
    </div>
    <div class="content">
      <template v-if="venderList.length > 0">
        <el-tabs v-model="activeVenderId">
          <el-tab-pane
            :label="vender.vender_info.vender_name"
            :name="vender.vender_info.vender_id"
            v-for="(vender, vIndex) in venderList"
            :key="vIndex"
          >
            <!-- <div class="part">
              <div class="info-item" v-for="(infoObj,iIndex) in vender.specification_info" :key="iIndex">
                <div class="ii-label">{{ infoObj.specification_name }}</div>
                <div class="ii-value">{{ infoObj.specification_value }}</div>
              </div>
            </div> -->
            <div class="part">
              <div class="sub-title">可做订单如下</div>
              <el-table
                :data="vender.template_info"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="template_id" label="ID">
                </el-table-column>
                <el-table-column prop="operator_id" sortable label="运营商"
                  :filters="[
                    { text: '移动', value: '移动' },
                    { text: '联通', value: '联通' },
                    { text: '电信', value: '电信' },
                  ]"
                  :filter-method="filterOperator"
                >
                </el-table-column>
                <el-table-column prop="prov_code" label="省份">
                </el-table-column>
                <el-table-column
                  prop="amount"
                  label="价格"
                  sortable
                  :filters="[
                    { text: '<10', value: 'lt10' },
                    { text: '10', value: '10' },
                    { text: '20', value: '20' },
                    { text: '30', value: '30' },
                    { text: '50', value: '50' },
                    { text: '100', value: '100' },
                    { text: '200', value: '200' },
                    { text: '300', value: '300' },
                    { text: '500', value: '500' },
                    { text: '800', value: '800' },
                    { text: '>800', value: 'gt800' }
                  ]"
                  :filter-method="filterAmount"
                >
                </el-table-column>
                <el-table-column prop="max_order_num" label="数量" sortable>
                </el-table-column>

                <el-table-column fixed="right" label="操作" min-width="120">
                  <template #default="scope">
                    <el-button
                      @click="acceptOrder(scope.row,vIndex)"
                      size="small"
                      type="success"
                      >接单</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else>
        <div class="tip">
          您可以点击【查询】按钮，查询此时可以做的订单有那些
        </div>
      </template>
    </div>
    <el-dialog title="接单" v-model="acceptDialogVisible" width="60%" center>
      <div class="accept-dialog-content">
        <div class="d-item">
          <div class="di-label">ID</div>
          <div class="di-value">{{ curTemplate.template_id }}</div>
        </div>
        <div class="d-item">
          <div class="di-label">运营商</div>
          <div class="di-value">{{ curTemplate.operator_id }}</div>
        </div>
        <div class="d-item">
          <div class="di-label">省份</div>
          <div class="di-value">{{ curTemplate.prov_code }}</div>
        </div>
        <div class="d-item">
          <div class="di-label">面值（元）</div>
          <div class="di-value">{{ curTemplate.amount }}</div>
        </div>
        <div class="d-item">
          <div class="di-label">可接单量</div>
          <div class="di-value">{{ curTemplate.max_order_num }}</div>
        </div>
        <div class="d-item">
          <div class="di-label">接单数量</div>
          <div class="di-value">
            <el-input
              v-model.number="curTemplate.order_num"
              placeholder="请输入接单数量"
              :max="curTemplate.max_order_num"
            ></el-input>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="acceptDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            :loading="getOrderLoading"
            @click="submitGetOrder"
            >确 定</el-button
          >
        </span>
      </template>
      
    </el-dialog>
  </div>
</template>

<script setup>
import { request } from '@/api/fetch'
import { onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { loadStore } from '@/store'
const activeVenderId = ref('')
const venderList = ref([])
const refreshLoading = ref(false)
const getOrderLoading = ref(false)
const acceptDialogVisible = ref(false)
const curTemplate = ref({})



async function getVender() {
  try {
    refreshLoading.value = true
    let data = await request('/getBeeVender')
    
    if (Array.isArray(data)) {
      data.forEach((item) => {
        item.template_info = item.template_info
          .filter((tempItem) => {
            return tempItem.order_num > 0
          })
          .map((tempItem) => {
            let template_specification_value =
              tempItem.template_specification_value
            let tempInfo = template_specification_value.split('|')
            return {
              template_id:tempItem.template_id,
              template_specification_value:tempItem.template_specification_value,
              operator_id: tempInfo[0],
              prov_code: tempInfo[1],
              amount: Number(tempInfo[2]),
              max_order_num: tempItem.order_num
            }
          })
          .sort((pre, next) => {
            return next.amount - pre.amount
          })
      })
      venderList.value = data

      activeVenderId.value = data[0].vender_info.vender_id
    }

    refreshLoading.value = false
    ElMessage({
      type: 'success',
      message: '请求成功'
    })
  } catch (error) {
    
  } finally{
    refreshLoading.value = false
  }
  
}
function filterOperator(value,row){
  // console.log('filterOperator value:',value)
  return row.operator_id === value
}
function filterAmount(value, row, column) {
  // console.log('filterAmount :',row,column)
  let amount = Number(row.amount)
  if (value === 'lt10') {
    return amount < 10
  } else if (value === 'gt800') {
    return amount > 800
  } else {
    return amount === Number(value)
  }
}
function acceptOrder(row) {
  console.log('row:',row)
  curTemplate.value = {
    template_id:row.template_id,
    operator_id: row.operator_id,
    prov_code: row.prov_code,
    amount: row.amount,
    max_order_num: row.max_order_num,
    order_num: 1
  }
  acceptDialogVisible.value = true
}
async function submitGetOrder() {
  if (!activeVenderId.value) {
    ElMessage({
      type: 'error',
      message: '渠道id不能为空'
    })
    return
  }
  if (!curTemplate.value.order_num) {
    ElMessage({
      type: 'error',
      message: '接单数量不能为空'
    })
    return
  }
  if(curTemplate.value.order_num > curTemplate.value.max_order_num){
    ElMessage({
      type: 'error',
      message: '接单数量不能大于最大数量'
    })
    return
  }
  getOrderLoading.value = true
  // 获取订单
  try {
    let res = await request('/getBeeOrder', {
      method: 'POST',
      body: {
        vender_id: activeVenderId.value,
        data: JSON.stringify({
          amount:curTemplate.value.amount,
          operator_id:curTemplate.value.operator_id,
          order_num:curTemplate.value.order_num,
          prov_code:curTemplate.value.prov_code,
        })
      }
    })
    if (res) {
      // 删除已经接单的订单
      let vIndex = venderList.value.findIndex(vItem=>{
        return vItem.vender_info.vender_id === activeVenderId.value
      })
      console.log('vIndex:',vIndex)
      let templateIndex = venderList.value[vIndex].template_info.findIndex(tItem=>{
        return tItem.template_id ===curTemplate.value.template_id
      })
      console.log('templateIndex:',templateIndex)
      venderList.value[vIndex].template_info.splice(templateIndex,1)
      
      ElMessage({
        type: 'success',
        message: '接单成功，可前往【已接订单】列表查看'
      })
      acceptDialogVisible.value = false
      return
    }
  } catch (error) {
    // ElMessage({
    //   type: 'error',
    //   message: '接单失败，请稍等片刻后，点击【查询】按钮重新查询订单'
    // })
  } finally{
    getOrderLoading.value = false
  }
  

  
}

onMounted(() => {
  // getVender()
})
</script>
<style lang="scss" scoped>
.content {
  .tip {
    text-align: center;
    font-weight: bold;
  }
  .part {
    margin-top: 20px;
    .info-item {
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      .ii-label {
        font-weight: bold;
        width: 120px;
      }
      .ll-value {
      }
    }
    .sub-title {
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
    }
    .el-table {
      margin-top: 20px;
    }
  }
}

</style>
<style lang="scss">
.accept-dialog-content {
  .d-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 20px;
    .di-label {
      font-weight: bold;
      width: 120px;
    }
  }
  .dialog-footer{
    margin-top: 20px;
    display: flex;
  }
}
</style>
